from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_cors import CORS

from toutiao.settings import Config
#只需要修改key即可获取指定配置类
from toutiao.settings import config_dict,setup_log
Config = config_dict['dev']
#日志
setup_log(Config)

app = Flask(__name__)


app.config.from_object(Config)
#创建SQLALCHEMY 实例
db = SQLAlchemy(app)
#redis实例
# redis_store=redis.Redis(host=Config.REDIS_HOST,port=Config.REDIS_PORT)
#current_app.属性 利于抽取代码
app.redis_store=redis.StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT)
#跨域
CORS(app)

#注册url的转换器,需添加在注册蓝图之前（蓝图被导入时路径中已使用转换器）
from toutiao.utils.converters import register_converters
register_converters(app)

#雪花算法生成id，能够确保唯一
from snowflake.id_worker import IdWorker
app.id_worker = IdWorker(datacenter_id=Config.DATACENTER_ID,
                        worker_id=Config.WORKER_ID,
                        sequence=Config.SEQUENCE)


#注册蓝图
from toutiao.apps.home import home_blueprint
app.register_blueprint(home_blueprint)

from toutiao.apps.user import user_blueprint
app.register_blueprint(user_blueprint)

#通过钩子函数，在每次请求前验证jwt中token
from flask import request,g
from auth.auth_jwt import verify_jwt

@app.before_request
def before_request():
    #初始化变量
    g.user_id = None
    g.is_fresh_token = None

    authorization = request.headers.get('Authorization')
    if authorization and authorization.startswith('Bearer '):
        token = authorization[7:]
        payload=verify_jwt(token)

        #接受jwt载荷中的数据，读取出来通过g变量保存，方便其他函数获取
        if payload:
            g.user_id = payload.get('user_id')
            g.is_refresh_token = payload.get('refresh')

